package com.hitqz.robot.driver.netty.strategy;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.util.concurrent.RateLimiter;
import com.hitqz.robot.driver.dto.AirQualityDto;
import com.hitqz.robot.driver.netty.protocol.message.TrackMessage;
import com.hitqz.robot.driver.util.TrackCacheUtil;
import com.hitqz.robot.driver.util.TrackToolkit;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * 消息解析，只做信息保存或者发布事件，不做业务逻辑处理
 */
@Slf4j
public class Track2BStrategy implements TrackMessageHandlerStrategy {

    private static final RateLimiter logLimiter = RateLimiter.create(1);

    @Override
    public void handle(ChannelHandlerContext ctx, TrackMessage message) {
        // 获取消息中的数据
        byte[] data = message.getData();
        byte mainCmd = data[0];
        byte subCmd = data[1];
        // 分配 ByteBuf 并将数据写入
        ByteBuf buffer = ctx.alloc().buffer(data.length);
        buffer.writeBytes(data);
        try {
            mainCmd = buffer.readByte();
            subCmd = buffer.readByte();
            if (subCmd == 0x02) {
                AirQualityDto lastAirQuality = Optional.ofNullable((AirQualityDto) TrackCacheUtil.get(TrackCacheUtil.KEY_AIR_QUALITY)).orElse(AirQualityDto.builder().build());
                short pm2Point5 = buffer.readShortLE();
                short tvoc = buffer.readShortLE();//tvoc数据
                short smoke = buffer.readShortLE();//烟雾数据（0：没有；1有）
                short temperature = buffer.readShortLE();//温度
                short humidity = buffer.readShortLE();//湿度
                short alcohol = buffer.readShortLE();//酒精
                short h2s = buffer.readShortLE();//硫化氢
                short nh = buffer.readShortLE();//氨气
                short noise = buffer.readShortLE();//噪音
                short pm10 = buffer.readShortLE();//pm10
                short ch4 = buffer.readShortLE();//ch4
                short gas = buffer.readShortLE();//可燃气体
                if (logLimiter.tryAcquire(60*5)){
                    log.info("[track]2B02 air:pm2.5{},tvoc:{},smoke:{},temperature:{},humidity:{},alcohol:{},h2s:{},nh:{},noise:{},pm10:{},ch4:{},gas:{}", pm2Point5, tvoc, smoke, temperature, humidity, alcohol, h2s, nh, noise, pm10, ch4, gas);
                }
                // 保存返回
                AirQualityDto airQualityDto = AirQualityDto.builder().
                        pm2Point5(pm2Point5).tvoc(tvoc).smoke(smoke).
                        temperature(temperature).humidity(humidity).alcohol(alcohol).h2s(h2s).nh(nh).noise(noise).pm10(pm10).ch4(ch4).gas(gas).build();
                BeanUtil.copyProperties(airQualityDto,lastAirQuality);
                TrackCacheUtil.put(TrackCacheUtil.KEY_AIR_QUALITY,lastAirQuality);
                // todo 报警
            }
            TrackToolkit.release(message, true, true);
        } catch (Exception e) {
            log.error("[track]deal  {}{}-message error,{}",String.format("%02x",mainCmd),String.format("%02x",subCmd),e.getMessage());
        } finally {
            // 确保 ByteBuf 在使用完后释放，防止内存泄漏
            buffer.release();
        }
    }

}
